using System;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;
using HengTong.Model.Db;
using HengTong.Model.Db.Hr;
using UUIDNext;


namespace HengTong.ViewModel.Person.SysPersonProfessionalTitleVms
{
    public partial class SysPersonProfessionalTitleVm : CrudVm<SysPersonProfessionalTitle>
    {
        public SysPersonProfessionalTitleVm()
        {
            SetInclude(x => x.Person);
            SetInclude(x => x.ProfessionalTitleType);
        }

        protected override void InitVM()
        {
        }

        public override async Task DoAddAsync()
        {
            // 加载ProfessionalTitleType导航属性
            if (Entity.ProfessionalTitleTypeId.HasValue)
            {
                Entity.ProfessionalTitleType = await DC.Set<SysPersonProfessionalTitleType>()
                    .FindAsync(Entity.ProfessionalTitleTypeId.Value);
            }

            // 验证资质类别为技能和职称时证书文件必填
            if (Entity.ProfessionalTitleType?.CategoryName == "技能" ||
                Entity.ProfessionalTitleType?.CategoryName == "职称")
            {
                if (Entity.CertificateDocumentId == null || Entity.CertificateDocumentId == Guid.Empty)
                {
                    MSD.AddModelError("CertificateFile", "资质类别为技能或职称时，证书文件为必填项");
                    return;
                }
            }

            Entity.ID = Uuid.NewDatabaseFriendly(Database.SqlServer);
            if (Entity is IBasePoco poco)
            {
                poco.CreateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.CreateTime = DateTime.Now;
                poco.UpdateTime = DateTime.Now;
            }

            await base.DoAddAsync();
        }

        public override async Task DoEditAsync(bool updateAllFields = false)
        {
            // 加载ProfessionalTitleType导航属性
            if (Entity.ProfessionalTitleTypeId.HasValue)
            {
                Entity.ProfessionalTitleType = await DC.Set<SysPersonProfessionalTitleType>()
                    .FindAsync(Entity.ProfessionalTitleTypeId.Value);
            }

            // 验证资质类别为技能和职称时证书文件必填
            if (Entity.ProfessionalTitleType?.CategoryName == "技能" ||
                Entity.ProfessionalTitleType?.CategoryName == "职称")
            {
                if (Entity.CertificateDocumentId == null || Entity.CertificateDocumentId == Guid.Empty)
                {
                    MSD.AddModelError("CertificateFile", "资质类别为技能或职称时，证书文件为必填项");
                    return;
                }
            }

            if (Entity is IBasePoco poco)
            {
                poco.UpdateBy = Wtm.LoginUserInfo?.ITCode;
                poco.UpdateTime = DateTime.Now;
            }

            await base.DoEditAsync(updateAllFields);
        }
    }
}